package com.huangfu.learning.javabase.java.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/7/14
 * Time: 10:51
 * Version: 1.0
 * Description:调用其他类的方法
 **/
public class InvokeOtherClassMethod {
    public static void main(String[] args) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName("com.huangfu.learning.javabase.java.reflect.User");
            // 调用satHello方法
            Method method = clazz.getMethod("sayHello");
            method.invoke(clazz.newInstance());

            //调用sayChina方法
            method = clazz.getMethod("sayChina", String.class);
            method.invoke(clazz.newInstance(), "huangfu"); //方法参数

            //调用set  get方法
            Object obj = clazz.newInstance();
            // set  Name大小写注意
            Method methodSet = obj.getClass().getMethod("set" + "Name", String.class);
            methodSet.invoke(obj, "huangfu");
            //get  Name大小写注意
            Method methodGet = obj.getClass().getMethod("get" + "Name");
            System.out.println(methodGet.invoke(obj));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public User(int age) {
        this.age = age;
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }

    public void sayHello() {
        System.out.println("User  sayHello  Hello World...");
    }

    public void sayChina(String name) {
        System.out.println(name + "  sayChina  ");
    }
}
